<?php
// +-----------------------   学吧->发现  -----------------------------------------------
// | Author: 杨正兵 <yzb321055156@163.com>
namespace app\api\controller;
use app\api\controller\CommonController;
use app\api\model\CommentModel;
use app\api\model\ImsXbFindModel;
use think\Validate;
use think\Db;
use think\Request;
class StudyclubController extends CommonController
{
    //状态（0-删除，1-待审核，2-审核通过，3-显示，4-禁止显示）
    protected $videoDisplayStatus = '0,1,2,3,4';

    private function get_php_file($filename) {
        return trim(substr(file_get_contents($filename), 15));
    }
    private function set_php_file($filename, $content) {
        $fp = fopen($filename, "w");
        fwrite($fp, "<?php exit();?>" . $content);
        fclose($fp);
    }
    /**
     * 学吧banner图片
     * @params int pic_cate banner类型 （1首页banner 、2学吧头部banner图）
     * @params int status 状态,1:显示;0:隐藏
     */
    public function bannerData()
    {
        $status = input('post.status');
        $pic_type = input('post.pic_cate');
        $rule = [
            'status' => 'require|number|in:0,1',
            'slide_id' => 'require|number|in:1,2'
        ];
        $msg = [
            'status.require' => 4002,
            'status.number' => 4004,
            'status.in' => 4008,
            'slide_id.require' => 4002,
            'slide_id.number' => 4004,
            'slide_id.in' => 4008,
        ];
        $data['status'] = $status;
        $data['slide_id'] = $pic_type;
        $validate = new Validate($rule, $msg);
        $checkResult = $validate->check($data);
        if(!$checkResult){
            $errcode = $validate->getError();
            return returnJson($errcode, $this->errTips[$errcode]);
        }

        $bannerInit = Db::name('slide_item');
        $bannerDataResult = $bannerInit->where($data)->limit(0, 2)->order('list_order desc')->select();
        if(count($bannerDataResult) == 0){
            return returnJson(3003, $this->errTips[3003]);
        }
        foreach ($bannerDataResult as $bv){
//            $bv['image'] = DOMAIN_URL.'upload/'.$bv['image'];
            $bv['image'] = cmf_get_image_url(str_replace("\\","/",$bv['image']));
            $datas[] = $bv;
        }
        return returnJson(200, '', $datas);
    }

    /**
     * 学吧“发现模块”页面分类
     * @params int cate_id分类id
     * @params int page 分页
     * @params int limit 每页显示数
     */
    public function studyClubCategory()
    {
//        $cate_id = input('post.cate_id');
//        $page = input('post.page');
//        $limit = input('post.limit');
//        $rule = [
//            'parent_id' => 'require|number|egt:1',
//            'page' => 'require|number|egt:1',
//            'limit' => 'require|number|egt:1',
//        ];
//        $msg = [
//            'parent_id.require' => 4002,
//            'parent_id.number' => 4004,
//            'parent_id.egt' => 4006,
//            'page.require' => 4002,
//            'page.number' => 4004,
//            'page.egt' => 4006,
//            'limit.require' => 4002,
//            'limit.number' => 4004,
//            'limit.egt' => 4006,
//
//        ];
//        $data['parent_id'] = $cate_id;
//        $data['page'] = $page;
//        $data['limit'] = $limit;
//        $validate = new Validate($rule, $msg);
//        $checkResult = $validate->check($data);
//        if(!$checkResult){
//            $errcode = $validate->getError();
//            return json([ERRCODE_KEY => $errcode, ERRMSG_KEY => $this->errTips[$errcode]]);
//        }
        $datas['status'] = 1;
        $datas['parent_id'] = 4;
        $bannerInit = Db::name('portal_category');
        $selectResult = $bannerInit->where($datas)->order('list_order desc')->field('id,parent_id as cate_id,name,more')->select();
        if(empty($selectResult)){
            return returnJson(3003, $this->errTips[3003]);
        }
        foreach($selectResult as $sv){
            $sv['more'] = cmf_get_image_url(str_replace("\\","/",json_decode($sv['more'])->thumbnail));
            $svs[] = $sv;
        }
        return returnJson(200, '', $svs);
    }

    /**
     * 学吧“发现和话题”分类
     * @params int cate_id分类id
     * @params int page 分页
     * @params int limit 每页显示数
     */
    public function studyClubFindAndThemeCategory()
    {

        $datas['status'] = 1;
        $datas['parent_id'] = 3;
        $bannerInit = Db::name('portal_category');
        $selectResult = $bannerInit->where($datas)->order('list_order desc')->limit(($page-1) * $limit, $limit)->field('id,parent_id as cate_id,name,more')->select();
        if(empty($selectResult)){
            return returnJson(3003, $this->errTips[3003]);
        }
        foreach($selectResult as $sv){
            $sv['more'] = cmf_get_image_url(str_replace("\\","/",json_decode($sv['more'])->thumbnail));
            $svs[] = $sv;
        }
        return returnJson(200, '', $svs);
    }


    /**
     * 学吧页面分类内页礼包
     * @params int cate_id 分类id
     * @params  int status 状态（0-删除，1-待审核，2-审核通过，3-显示，4-禁止显示）
     * @params int page 分页
     * @params int limit 每页显示数量
     * @params int order 排序（按时间排序） 1最新时间排序  2最近旧时间排序
     */
    public function categoryDetailList()
    {
        $cate_id = input('post.cate_id');
        $page = input('post.page');
        $limit = input('post.limit');
        $status = input('post.status');
        $order = input('post.order');
        $rule = [
            'type_id' => 'require|number|egt:1',
            'page' => 'require|number|egt:1',
            'limit' => 'require|number|egt:1',
            'status' => 'require|number|in:'.$this->videoDisplayStatus,
            'order' => 'require|number|in:1,2'
        ];
        $msg = [
            'type_id.require' => 4002,
            'type_id.number' => 4004,
            'type_id.egt' => 4006,
            'page.require' => 4002,
            'page.number' => 4004,
            'page.egt' => 4006,
            'limit.require' => 4002,
            'limit.number' => 4004,
            'limit.egt' => 4006,
            'status.require' => 4002,
            'status.number' => 4004,
            'status.in' => 4008,
            'order.require' => 4002,
            'order.number' => 4004,
            'order.in' => 4008,
        ];
        $data['type_id'] = $cate_id;
        $data['page'] = $page;
        $data['limit'] = $limit;
        $data['status'] = $status;
        $data['order'] = $order;
        $validate = new Validate($rule, $msg);
        $checkResult = $validate->check($data);
        if(!$checkResult){
            $errcode = $validate->getError();
            return returnJson($errcode, $this->errTips[$errcode]);
        }

        $videoInit = Db::name('ims_xb_find');
        $datas = [
            'status' =>$status,
            'type_id' => $cate_id
        ];
        $selectResult = $videoInit->where($datas)->limit(($page-1) * $limit, $limit)->order('create_time desc')->field('id,type_id as cate_id,intro,cover_pic,vedio_link,create_time,like_amount')->select();

        if(count($selectResult) == 0){
            return returnJson(3003, $this->errTips[3003]);
        }
        $count = $videoInit->where($datas)->count();
        foreach($selectResult as $sv){
            //$sv['cover_pic'] = DOMAIN_URL.'upload/'.$sv['cover_pic'];
            $sv['cover_pic'] = cmf_get_image_url(str_replace("\\","/",$sv['cover_pic']));;
            $resData[] = $sv;
        }
        return returnJson(200, '', ['count'=>$count, 'data'=>$resData]);
    }

    /**
     * 学吧body中间部分内容
     * @params int page分页
     * @params int limit 每页显示数量
     * @params  int status 状态（0-删除，1-待审核，2-审核通过，3-显示，4-禁止显示）
     * 注：标签（0-无，1-推荐，2-职业素养，3-销售达人炼成秘籍，4-销售达人练成秘籍）
     */
    public function studyclubVideoList()
    {
        $page = input('post.page');
        $limit = input('post.limit');
        $status = input('post.status');
        $rule = [
            'page' => 'require|egt:1|number|float',
            'limit' => 'require|egt:1|number|float',
            'status' => 'require|egt:1|number|in:'.$this->videoDisplayStatus,
        ];
        $msg = [
            'page.require' => 4002,
            'page.number' => 4004,
            'page.egt' => 4006,
            'page.float' => 4007,
            'limit.require' => 4002,
            'limit.number' => 4004,
            'limit.egt' => 4006,
            'limit.float' => 4007,
            'status.require' => 4002,
            'status.number' => 4004,
            'status.egt' => 4006,
            'status.in' => 4008
        ];
        $data['page'] = $page;
        $data['limit'] = $limit;
        $data['status'] = $status;
        $validate = new Validate($rule, $msg);
        $checkResult = $validate->check($data);
        if(!$checkResult){
            $errcode = $validate->getError();
            return returnJson($errcode, $this->errTips[$errcode]);
        }
        $xuebaInit = Db::name('ims_xb_find');
        //status   状态（0-删除，1-待审核，2-审核通过，3-显示，4-禁止显示）

        $selectResult = $xuebaInit->where('status', $status)->limit(($page - 1) * $limit, $limit)->field('id,title,label,type_id,cover_pic,share_amount')->select();
        $count = $xuebaInit->where('status', $status)->count();
        if(empty($selectResult) || $count == 0){
            return returnJson(3003, $this->errTips[3003]);
        }
        foreach ($selectResult as $sv){
            //$sv['cover_pic'] = DOMAIN_URL.'upload/'.$sv['cover_pic'];
            $sv['cover_pic'] = cmf_get_image_url(str_replace("\\","/",$sv['cover_pic']));
            $svs[] = $sv;
        }
        return returnJson(200, '', ['count'=>$count, 'data'=>$svs]);
    }

    /**
     * 学吧body中间部分内容“单个视频详情”
     * @params int video_id 视频id
     * @params int status 状态（0-删除，1-待审核，2-审核通过，3-显示，4-禁止显示）
     * 注：字段label 标签（0-无，1-推荐，2-职业素养，3-销售达人炼成秘籍，4-销售达人练成秘籍）
     */
    public function studyclubVideoDetail()
    {
        $video_id = input('post.video_id');
        $status = input('post.status');
        $token = input('post.token_key');
        $rule = [
            'id' => 'require|number|egt:1',
            'status' => 'require|number|egt:1|in:'.$this->videoDisplayStatus,
        ];
        $msg = [
            'id.require' => 4002,
            'id.number' => 4004,
            'id.egt' => 4006,
            'status.require' => 4002,
            'status.number' => 4004,
            'status.egt' => 4006,
            'status.in' => 4008,
        ];
        $data = [
            'id' =>$video_id,
            'status' => $status,
        ];
        $validate = new Validate($rule, $msg);
        $checkResult = $validate->check($data);
        if(!$checkResult){
            $errcode = $validate->getError();
            return returnJson($errcode, $this->errTips[$errcode]);
        }

        /*验证token是否有效  --------  Start  -----------*/
        if(!empty($token)){
            $verifyToken = $this->verifyToken($token);
            if ( $verifyToken != '1111') {return $verifyToken;}
            $loginUserId = $this->user_id;
        }

        /*验证token是否有效  --------  End  -----------*/

        //$videoInit = Db::name('ims_xb_find');
        $userfollowInit = Db::name('ims_user_follow');
        $videoInit = new ImsXbFindModel();
        $videoResult = $videoInit->where($data)->field('id,title,vedio_link,intro,user_id,label,create_time')->find();
        if(empty($videoResult)){
            return returnJson(3003,  $this->errTips[3003]);
        }
        $labels = [1 => '每周热门推荐',2 => '职业素养',3 => '销售达人炼成秘籍',4 => '销售达人炼成秘籍'];

        $getuserinfo = $videoResult->getuserinfo;//获取用户信息

        //判断关注状态
        if(isset($loginUserId) && !empty($loginUserId)){
            $followMap['user_id'] = $loginUserId;
            $followMap['is_user_id'] = $videoResult['user_id'];
            $checkFollowUser = $userfollowInit->where($followMap)->find();
            if(empty($checkFollowUser) || $checkFollowUser['status'] == 0){
                $videoResult['followUserStatu'] = 0;
            }else{
                $videoResult['followUserStatu'] = 1;
            }
        }else{
            $videoResult['followUserStatu'] = 0;
        }

        $videoResult['label'] = $labels[$videoResult['label']];//获取标签名称
        $videoResult['video_score'] = ($videoResult->getvideoscore[0]->avg) ? ($videoResult->getvideoscore[0]->avg) : 0;//获取评分
        $videoResult['vedio_link'] = cmf_get_image_url(str_replace("\\","/",$videoResult['vedio_link'])); //获取视频地址
        $videoResult['video_look_count'] = count($videoResult->getlookcount);//获取观看人数量
        $videoResult['user_name'] = $getuserinfo['staff_name'];//获取观看人数量
        $videoResult['user_pic'] = $getuserinfo['staff_pic'];//获取观看人数量
        $videoResult['user_deptname'] = $getuserinfo['staff_deptname'];//获取观看人数量

        unset($videoResult['getuserinfo']);
        unset($videoResult['getvideoscore']);
        unset($videoResult['getlookcount']);

        return returnJson(200, '', $videoResult);
    }

    /**
     * 视频点赞
     * @params int video_id
     * @params int token_key
     * 注：user_link数据表   字段type_status //1来自portal_post表（话题），2来自comment表（评论），3来自ims_xb_find（视频）
     */
    public function videolink()
    {
        $video_id = input('post.video_id');

        $token = input('post.token_key');

        $rule = [
            'object_id' => 'require|number',
            'token' => 'require'
        ];
        $msg = [
            'object_id.require' => 4002,
            'object_id.number' => 4004,
            'token.require' => 4002,

        ];
        $data['object_id'] = $video_id;
        $data['token'] = $token;
        $validate = new Validate($rule, $msg);
        $checkResult = $validate->check($data);
        if(!$checkResult){
            $errcode = $validate->getError();
            return returnJson($errcode, $this->errTips[$errcode]);
        }

        /*验证token是否有效  --------  Start  -----------*/
        $verifyToken = $this->verifyToken($token);
        if ( $verifyToken != '1111') {return $verifyToken;}
        /*验证token是否有效  --------  End  -----------*/

        $userlinkInit = Db::name('user_like');
        $xmsXbFindInit = Db::name('ims_xb_find');

        $checkVideo = $xmsXbFindInit->find($video_id);
        if(empty($checkVideo)){
            return returnJson(2004, $this->errTips[2004]);
        }

        $datas['user_id'] = $this->user_id;
//        $datas['user_id'] = 1;
        $datas['type_status'] = 3;
        $datas['object_id'] = $video_id;

        $userlinkResult = $userlinkInit->where($datas)->find();

        if(empty($userlinkResult)){
            $datas['create_time'] = CURRENT_TIME;
            $datas['delete_time'] = CURRENT_TIME;
            $userlinkInit->insertGetId($datas);
            return returnJson(200, '', ['linkStatus' => 0]);
        }elseif($userlinkResult['delete_time'] == null){
            $updatedata['delete_time'] = CURRENT_TIME;
            $userlinkInit->where($datas)->update($updatedata);
            return returnJson(200, '', ['linkStatus' => 0]);
        }elseif ($userlinkResult['delete_time']){
            $updatedata['delete_time'] = null;
            $userlinkInit->where($datas)->update($updatedata);
            return returnJson(200, '', ['linkStatus' => 0]);
        }
    }

    /**
     * 视频收藏
     * @params int video_id
     * @params int token_key
     * 注：user_link数据表   字段type_status //1来自portal_post表（话题），2来自comment表（评论），3来自ims_xb_find（视频）
     */
    public function videocollect()
    {
        $video_id = input('post.video_id');
        $token = input('post.token_key');

        $rule = [
            'object_id' => 'require|number',
            'token' => 'require'
        ];
        $msg = [
            'object_id.require' => 4002,
            'object_id.number' => 4004,
            'token.require' => 4002,
        ];
        $data['object_id'] = $video_id;
        $data['token'] = $token;
        $validate = new Validate($rule, $msg);
        $checkResult = $validate->check($data);
        if(!$checkResult){
            $errcode = $validate->getError();
            return returnJson($errcode, $this->errTips[$errcode]);
        }

        /*验证token是否有效  --------  Start  -----------*/
        $verifyToken = $this->verifyToken($token);
        if ( $verifyToken != '1111') {return $verifyToken;}
        /*验证token是否有效  --------  End  -----------*/

        $userfavoriteInit = Db::name('user_favorite');
        $xmsXbFindInit = Db::name('ims_xb_find');

        $checkVideo = $xmsXbFindInit->find($video_id);
        if(empty($checkVideo)){
            return returnJson(2004, $this->errTips[2004]);
        }

        $datas['user_id'] = $this->user_id;
//        $datas['user_id'] = 4;
        $datas['type_status'] = 3;
        $datas['object_id'] = $video_id;

        $userlinkResult = $userfavoriteInit->where($datas)->find();

        if(empty($userlinkResult)){
            $datas['create_time'] = CURRENT_TIME;
            $datas['delete_time'] = CURRENT_TIME;
            $userfavoriteInit->insertGetId($datas);
            return returnJson(200, '', ['collectStatus' => 1]);
        }elseif($userlinkResult['delete_time'] == null){
            $updatedata['delete_time'] = CURRENT_TIME;
            $userfavoriteInit->where($datas)->update($updatedata);
            return returnJson(200, '', ['collectStatus' => 1]);
        }elseif ($userlinkResult['delete_time']){
            $updatedata['delete_time'] = null;
            $userfavoriteInit->where($datas)->update($updatedata);
            return returnJson(200, '', ['collectStatus' => 0]);
        }

    }

    /**
     * 学吧视频详情->关注用户
     * @params string token_key
     * @params int user_id 被关注用户的id
     */
    public function followuser()
    {
        $token = input('post.token_key');
        $user_id = input('post.user_id');
        $rule = [
            'token' => 'require|min:32',
            'user_id' => 'require|number'
        ];
        $msg = [
            'token.require' => 4002,
            'token.min' => 4001,
            'user_id.require' => 4002,
            'user_id.number' => 4004,
        ];

        $data['token'] = $token;
        $data['user_id'] = $user_id;
        $validate = new Validate($rule, $msg);
        $checkParam = $validate->check($data);
        if(!$checkParam){
            $errcode = $validate->getError();
            return returnJson($errcode, $this->errTips[$errcode]);
        }

        //判断token有效性
        $checktoken = $this->verifyToken($token);
        if($checktoken != 1111){
            return $checktoken;
        }
        $login_userId = $this->user_id;
//        $login_userId = 6;
        $userInit = Db::name('ims_member');
        $userFollowInit = Db::name('ims_user_follow');
        $checkWhereMap['id'] = ['in', [$login_userId, $user_id]];
        $checkUserResult = $userInit->where($checkWhereMap)->field('id')->select();

        if(empty($checkUserResult) || count($checkUserResult) != 2){
            return returnJson(2004, $this->errTips[2004]);//数据不存在（即返回“非法访问”）
        }
        $whereMap = [
            'user_id' => $login_userId,
            'is_user_id' => $user_id,
        ];

        $queryUserFollowInfo = $userFollowInit->where($whereMap)->find();
        if(empty($queryUserFollowInfo)){
            $whereMap['status'] = 1;
            $whereMap['create_time'] = time();
            $userFollowInit->insertGetId($whereMap);
            return returnJson(200, $this->errTips[200]);
        }elseif(!empty($queryUserFollowInfo) && $queryUserFollowInfo['status'] == 0){
            $updateStatus = $userFollowInit->where($whereMap)->update(['status' => 1]);
            return returnJson(200, $this->errTips[200]);
        }elseif(!empty($queryUserFollowInfo) && $queryUserFollowInfo['status'] == 1){
            $updateStatus = $userFollowInit->where($whereMap)->update(['status' => 0]);
            return returnJson(200, $this->errTips[200]);
        }
    }

    /**
     * 相关课件视频列表
     * @params int video_id
     */
    public function aboutvideolist()
    {
        $video_id = input('post.video_id');
        $page = input('post.page');
        $limit = input('post.limit');
        $rule = [
            'object_id' => 'require|number',
            'page' => 'require|number|egt:1',
            'limit' => 'require|number|egt:1'
        ];
        $msg = [
            'object_id.require' => 4002,
            'object_id.number' => 4004,
            'page.require' => 4002,
            'page.number' => 4004,
            'page.egt' => 4006,
            'limit.require' => 4002,
            'limit.number' => 4004,
            'limit.egt' => 4006,
        ];
        $data['object_id'] = $video_id;
        $data['page'] = $page;
        $data['limit'] = $limit;

        $validate = new Validate($rule, $msg);
        $checkResult = $validate->check($data);
        if(!$checkResult){
            $errcode = $validate->getError();
            return returnJson($errcode, $this->errTips[$errcode]);
        }

        $xbFindInit = Db::name('ims_xb_find');
        $checkIdExists = $xbFindInit->field('id')->find($video_id);

        if(empty($checkIdExists)){
            return returnJson(2004, $this->errTips[2004]);//非法操作（非法提交视频id）
        }
        $aboutVideoDataList = $xbFindInit->where(['about_video_id' => $video_id])->select();
        if(empty($aboutVideoDataList)){
            return returnJson(3003, $this->errTips[3003]);
        }
        return returnJson(200, '', $aboutVideoDataList);
    }

    /**
     * 视频评论
     * @params int video_id 视频id
     * @params int page 分页
     * @params int limit 每页显示数量
     */
    public function videocomment()
    {

        $video_id = input('post.video_id');
        $page = input('post.page');
        $limit = input('post.limit');
        $token = input('post.token_key');

        $rule = [
            'video_id' => 'require|number',
            'page' => 'require|number|egt:1',
            'limit' => 'require|number|egt:1'
        ];
        $msg = [
            'video_id.require' => 4002,
            'video_id.number' => 4004,
            'page.require' => 4002,
            'page.number' => 4004,
            'page.egt' => 4006,
            'limit.require' => 4002,
            'limit.number' => 4004,
            'limit.egt' => 4006,
        ];
        $data['video_id'] = $video_id;
        $data['page'] = $page;
        $data['limit'] = $limit;
        $validate = new Validate($rule, $msg);
        $checkParams = $validate->check($data);
        if(!$checkParams){
            $errcode = $validate->getError();
            return returnJson($errcode, $this->errTips[$errcode]);
        }

        $userInit = Db::name('ims_xb_find');
        $Comment_m = new CommentModel();
        $queryVideo = $userInit->field('id,title,user_id')->find($video_id);
        if(empty($queryVideo)){
            return returnJson(3003, $this->errTips[3003]);
        }
        $commentMap = [
            'object_id' => $video_id,
            'status' => 1,
        ];

        if(strlen($token) >= 1){
            $checktoken = $this->verifyToken($token);
            if($checktoken != 1111){
                return $checktoken;
            }
            $loginUserId = $this->user_id;
        }


        //查询评论
        $videoResult = $Comment_m->where($commentMap)->limit(($page - 1) * $limit, $limit)->field('object_id,user_id,content,id,create_time')->order('create_time DESC')->select();
        if(empty($videoResult)){
            return returnJson(3003, $this->errTips[3003]);
        }
        foreach ($videoResult as $vc){
            $userinfo = $vc->getuserinfo;
            $getuserlike = $vc->getuserlike;

            $commentData = $vc->toArray();
            $commentData['user_name'] = $userinfo['staff_name'];
            $commentData['user_pic'] = $userinfo['staff_pic'];

            //判断用户是否已经点赞
            foreach ($getuserlike as $gv){
                $loginUserId_verify[] = $gv['user_id'];
            }

            if(!isset($loginUserId)){
                $commentData['likeStatus'] = 0;
            }else{
                if(in_array($loginUserId, $loginUserId_verify)){
                    $commentData['likeStatus'] = 1;
                }else{
                    $commentData['likeStatus'] = 0;
                }
            }

            unset($loginUserId_verify);//废弃数组

            unset($commentData['getuserlike']);
            unset($commentData['object_id']);
            unset($commentData['getuserinfo']);
            $commentDatas[] = $commentData;
        }
        return returnJson(200, $commentDatas);
    }

    /**
     * 点赞评论
     * @params int comment_id 评论id
     * @params string token_key 访问接口密钥
     */
    public function commentlink()
    {
        $comment_id = input('post.comment_id');
        $token = input('post.token_key');
        $rule = [
            'comment_id' => 'require|number',
            'token' => 'require',
        ];
        $msg = [
            'comment_id.requrie' => 4002,
            'comment_id.number' => 4004,
            'token.require' => 4002,
        ];
        $data['comment_id'] = $comment_id;
        $data['token'] = $token;
        $validate = new Validate($rule, $msg);
        $checkParam = $validate->check($data);
        if(!$checkParam){
            $errcode = $validate->getError();
            return returnJson($errcode, $this->errTips[$errcode]);
        }

        //校验token
        $checktoken = $this->verifyToken($token);
        if($checktoken != 1111){
            return $checktoken;
        }

        $loginUserId = $this->user_id;

        //数据操作
        $userlikeInit = Db::name('user_like');
        $commentInit = Db::name('comment');
        $userInit = Db::name('ims_member');

        $queryLoginUserInfo = $userInit->find($loginUserId);//查询登录用户是否存在
        $commentResult = $commentInit->find($comment_id);//查询被点赞用户是否存在

        if(empty($queryLoginUserInfo) || empty($commentResult)){
            return returnJson(2004, $this->errTips[2004]);
        }

        $whereMap = [
            'user_id' =>$loginUserId,
            'object_id' =>$comment_id,
            'type_status' =>2,
        ];
        $queryResult = $userlikeInit->where($whereMap)->find();
        if(empty($queryResult)){

            $whereMap['create_time'] = CURRENT_TIME;
            $userlikeInit->insertGetId($whereMap);
            return returnJson(200, 'success');
        }elseif(!empty($queryResult) && $queryResult['delete_time'] == 0){
            $wheres['delete_time'] = CURRENT_TIME;
            $userlikeInit->where($whereMap)->update($wheres);
            return returnJson(200, 'success');
        }elseif(!empty($queryResult) && $queryResult['delete_time'] != 0){
            $wheres['delete_time'] = 0;
            $userlikeInit->where($whereMap)->update($wheres);
            return returnJson(200, 'success');
        }
    }

    /**
     * 对视频发布评论
     * @params  int video_id 视频id
     * @params token_key 访问接口密钥
     * @params string content 评论内容  //限制字数200
     */
    public function commentvideo()
    {
        $video_id = input('post.video_id');
        $token = input('post.token_key');
        $content = input('post.content');
        $rule = [
            'video_id' => 'require|number',
            'token' => 'require|min:1',
            'content' => 'require',
        ];
        $msg = [
            'video_id.require' => 4002,
            'video_id.number' => 4004,
            'token.require' => 4002,
            'content.require' => 4002,
            'content.length' => 4010,
        ];
        $data['video_id'] = $video_id;
        $data['token'] = $token;
        $data['content'] = $content;

        $validate = new Validate($rule, $msg);
        $checkParam = $validate->check($data);
        if(!$checkParam){
            $errcode = $validate->getError();
            return returnJson($errcode, $this->errTips[$errcode]);
        }
        $checktoken = $this->verifyToken($token);
        if($checktoken != 1111){
            return $checktoken;
        }
        $user_id = $this->user_id;
//        $user_id = 5;

        //屏蔽进行恶意评论操作的用户
        $filename = APP_PATH.'api/cache/Commentcache.php';
        $getVideoCache = $this->get_php_file($filename);
        $cachetoArray = json_decode($getVideoCache);//object
        if(!empty($cachetoArray)){
            foreach ($cachetoArray as $ctv){
                //否则更新数据
                $cachedata = [
                    'video_id' => $ctv->video_id,
                    'user_id' => $ctv->user_id,
                    'expire_time' => CURRENT_TIME + COMMENT_EXPIRE_TIME
                ];
                $cachefdata[] = $cachedata;
                $useridArray[] = $ctv->user_id;
                $videoidArray[] = $ctv->video_id;
                if($ctv->user_id == $user_id && $ctv->video_id == $video_id && $ctv->expire_time >= CURRENT_TIME){
                    return returnJson(2005, $this->errTips[2005]);
                }
            }

            if(!in_array($video_id, $videoidArray) || !in_array($user_id, $useridArray)){
                $pusharray = [
                    'video_id' => $video_id,
                    'user_id' => $user_id,
                    'expire_time' => CURRENT_TIME + COMMENT_EXPIRE_TIME
                ];
                array_push($cachefdata, $pusharray);
                $str = json_encode($cachefdata);
                $this->set_php_file($filename, $str);
            }
        }

        //数据库插入数据操作
        $commentInit = Db::name('comment');
        $inserMap = [
            'object_id' => $video_id,
            'user_id' => $user_id,
            'delete_time' => 0,
            'create_time' => CURRENT_TIME,
            'status' => 1,
            'content' => $content,
        ];

        $insertResult = $commentInit->insertGetId($inserMap);
        if(!$insertResult){
            return returnJson(3002, $this->errTips[3002]);
        }

        //写入或更新缓存
        if(isset($cachefdata)){
            foreach($cachefdata as $updateV){
                if($updateV['user_id'] == $user_id && $updateV['video_id'] == $video_id){
                    $updateV['expire_time'] = CURRENT_TIME + COMMENT_EXPIRE_TIME;
                }
                $fupdates[] = $updateV;
            }
            $str = json_encode($fupdates);
            $this->set_php_file($filename, $str);
        }else{

            $cachefdata = [];
            $pusharray = [
                'video_id' => $video_id,
                'user_id' => $user_id,
                'expire_time' => CURRENT_TIME + COMMENT_EXPIRE_TIME
            ];
            array_push($cachefdata, $pusharray);
            $str = json_encode($cachefdata);
            $this->set_php_file($filename, $str);
        }

        return returnJson(200, 'success');
    }

    public function getfile()
    {
        $filename = APP_PATH.'api/cache/Commentcache.php';
        $res = $this->get_php_file($filename);
        $toArray = json_decode($res);
        foreach ($toArray as $tv){
            if($tv->user_id == 3 && $tv->video_id == 1 && $tv->expire_time >= CURRENT_TIME){
                return '已过期,不能频繁评论';
            }else{
                return '正常使用';
            }

        }


    }

    public function setfile()
    {
        $filename = APP_PATH.'api/cache/Commentcache.php';
        $data = [
            [
                'video_id' => 1,
                'user_id' => 3,
                'expire_time' => CURRENT_TIME + 60
            ],
            [
                'video_id' => 3,
                'user_id' => 2,
                'expire_time' => CURRENT_TIME + 60
            ],

        ];
        $str = json_encode($data);

        $this->set_php_file($filename, $str);
    }



    /**
     * 学吧“发现 和 话题”
     * @params int cate_id 分类id
     */
    public function findAndThemeCategory()
    {
        $cate_id = input('post.cate_id');
        $rule = [
            'parent_id' => 'require|number|egt:1'
        ];
        $msg = [
            'parent_id.require' => 4002,
            'parent_id.number' => 4004,
            'parent_id.egt' => 4006,
        ];
        $data['parent_id'] = $cate_id;
        $validate = new Validate($rule, $msg);
        $checkValidate = $validate->check($data);
        if(!$checkValidate){
            $errcode = $validate->getError();
            return returnJson($errcode, $this->errTips[$errcode]);
        }
        $cateInit = Db::name('portal_category');
        $dataQueryResult = $cateInit->where('parent_id', $cate_id)->field('id, name')->select();
        if(empty($dataQueryResult)){
            return returnJson(3003, $this->errTips[3003]);
        }
        return returnJson(200, '', $dataQueryResult);
    }


}